//
//  HomeViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/3/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "HomeViewController.h"
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "GruphotoAppDelegate.h"
#import "GruphotoTabBarController.h"
#import "User.h"

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"background_navigation_bar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

@implementation HomeViewController
@synthesize email;

#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(facebookDidLoginToAccessApp:) name:GPFacebookSessionDidOpenedNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.email = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Action methods
- (IBAction)loginButtonPressed:(id)sender {
    LoginViewController *loginViewController = [[LoginViewController alloc] initWithNibName:@"LoginViewController"
                                                                                     bundle:nil];
    [self.navigationController pushViewController:loginViewController
                                         animated:YES];
    [loginViewController release];
}

- (IBAction)createAccountButtonPressed:(id)sender {
    RegisterViewController *registerViewController = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController"
                                                                                              bundle:nil];
    [self.navigationController pushViewController:registerViewController animated:YES];
    [registerViewController release];
}

- (IBAction)loginWithFacebookButtonPressed:(id)sender {
    facebookLoginType = GPFacebookLoginTypeAccessApp;
/*
    [FBSession.activeSession openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
        [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
            FBGraphObject *resultObject = (FBGraphObject *)result;
            NSString *socialId = [resultObject objectForKey:@"id"];
            self.email = [resultObject objectForKey:kEmail];
            NSString *photo = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture", socialId];
            NSString *firstName = [resultObject objectForKey:kFirstName];
            NSString *lastName = [resultObject objectForKey:kLastName];
            
            [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Logging in..."];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:socialId forKey:kSocialId];
            [params setObject:email forKey:kEmail];
            [params setObject:firstName forKey:kFirstName];
            [params setObject:lastName forKey:kLastName];
            [params setObject:photo forKey:kPhoto];
            [params setObject:deviceToken forKey:kDeviceToken];
            
            NSLog(@"params: %@", params);
            [TNHRequestHelper sendPostRequest:kLoginWithFacebookUrl
                                      withTag:RequestTagLoginWithFacebook
                                       params:params
                                     delegate:self];
        }];
    }];
*/
    if (FBSession.activeSession.isOpen) {
        [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
            FBGraphObject *resultObject = (FBGraphObject *)result;
            NSString *socialId = [resultObject objectForKey:@"id"];
            self.email = [resultObject objectForKey:kEmail];
            NSString *photo = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture", socialId];
            NSString *firstName = [resultObject objectForKey:kFirstName];
            NSString *lastName = [resultObject objectForKey:kLastName];
            
            [[GruphotoAppDelegate sharedDelegate] showHUDWithStatus:@"Logging in..."];
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            [params setObject:socialId forKey:kSocialId];
            [params setObject:email forKey:kEmail];
            [params setObject:firstName forKey:kFirstName];
            [params setObject:lastName forKey:kLastName];
            [params setObject:photo forKey:kPhoto];
            NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:kDeviceToken];
            [params setObject:deviceToken forKey:kDeviceToken];
            
            NSLog(@"params: %@", params);
            [TNHRequestHelper sendPostRequest:kLoginWithFacebookUrl
                                      withTag:RequestTagLoginWithFacebook
                                       params:params
                                     delegate:self];
        }];
    }
    else {
        [[GruphotoAppDelegate sharedDelegate] openSessionWithAllowLoginUI:YES];        
    }
}

- (void)facebookDidLoginToAccessApp:(NSNotification *)notification {
    if (facebookLoginType == GPFacebookLoginTypeAccessApp) {
        [self loginWithFacebookButtonPressed:nil];
    }
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    NSLog(@"data: %@", request.responseString);
    
    NSDictionary *response = (NSDictionary *)[TNHRequestHelper objectWithString:request.responseString];
    NSInteger errorCode = [[response objectForKey:kErrorCode] integerValue];
    if (errorCode == ErrorCodeNone) {       
        User *_loggedInUser = [[User alloc] init];
        _loggedInUser.email = email;
        _loggedInUser.firstName = [response objectForKey:kFirstName];
        _loggedInUser.lastName = [response objectForKey:kLastName];
        _loggedInUser.numberOfPhotos = [[response objectForKey:kNumPhoto] integerValue];
        _loggedInUser.userId = [[response objectForKey:kUserId] integerValue];
        if (![[response objectForKey:kPhoto] isEqual:[NSNull null]]) {
            _loggedInUser.avatarUrl = [response objectForKey:kPhoto];
        }
        if (![[response objectForKey:kSocialId] isEqual:[NSNull null]]) {
            _loggedInUser.socialId = [response objectForKey:kSocialId];
        }
        _loggedInUser.token = [response objectForKey:kUserToken];
        _loggedInUser.numberOfLikes = [[response objectForKey:kNumLike] integerValue];
        _loggedInUser.numberOfFollowers = [[response objectForKey:kNumFollower] integerValue];
        _loggedInUser.loginType = LoginTypeFacebook;
        [GruphotoAppDelegate sharedDelegate].loggedInUser = _loggedInUser;
        [_loggedInUser release];
        
        GruphotoTabBarController *tabbarController = [[GruphotoTabBarController alloc] init];
        [self presentModalViewController:tabbarController animated:YES];
        [tabbarController release];
    }
    else {
        NSString *errorMessage = [response objectForKey:kErrorMessage];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Login error"
                                                            message:errorMessage
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [[GruphotoAppDelegate sharedDelegate] hideHUD];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                        message:@"Internet is down, please try again"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

@end
